package com.md.infrastructure.persistence.repository.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.md.base.BaseRepositoryImpl;
import com.md.domain.model.bo.QueryLogsBO;
import com.md.domain.model.po.Logs;
import com.md.infrastructure.persistence.mapper.LogsMapper;
import com.md.infrastructure.persistence.repository.LogsRepository;
import com.md.util.ObjectUtil;
import org.springframework.stereotype.Repository;
import org.springframework.util.ObjectUtils;


/**
 * @author 刘骄阳
 * 2022-06-12 1:22
 */
@Repository
public class LogsRepositoryImpl extends BaseRepositoryImpl<Logs, LogsMapper> implements LogsRepository {

  public LogsRepositoryImpl(final LogsMapper mapper) {
    super(mapper);
  }

  @Override
  public IPage<Logs> selectRootLoByPage(final QueryLogsBO queryLogsBO) {
    Page<Logs> page = new Page<>(queryLogsBO.getPageNum(), queryLogsBO.getPageSize());
    LambdaQueryWrapper<Logs> wrapper = new LambdaQueryWrapper<>();
    wrapper
      // 数据要小于该时间
      .le(Logs::getOperateDate, queryLogsBO.getCursor())
      // 操作类型
      .in(ObjectUtil.notEmpty(queryLogsBO.getOperation()), Logs::getOperation, queryLogsBO.getOperation())
      // 调用时间
      .le(ObjectUtil.notEmpty(queryLogsBO.getMaxTime()), Logs::getConsumingTime, queryLogsBO.getMaxTime())
      // 大于等于最小时间
      .ge(ObjectUtil.notEmpty(queryLogsBO.getMinTime()), Logs::getConsumingTime, queryLogsBO.getMinTime())
      .isNull(queryLogsBO.getOnlyRoot(), Logs::getParentId)
      .orderByDesc(Logs::getId);
    return mapper.selectPage(page, wrapper);
  }

  @Override
  public Logs selectByDataId(final String dataId) {
    LambdaQueryWrapper<Logs> wrapper = new LambdaQueryWrapper<>();
    wrapper.eq(Logs::getDataId, dataId);
    return mapper.selectOne(wrapper);
  }

  /**
   * 初始化wrapper
   *
   * @param logs    实体
   * @param maxTime 最大时间
   * @param minTime 最小时间
   * @return wrapper
   */
  private LambdaQueryWrapper<Logs> initSelectDate(final Logs logs,
                                                  final Long maxTime,
                                                  final Long minTime) {
    LambdaQueryWrapper<Logs> wrapper = new LambdaQueryWrapper<>(logs);
    // 小于等于最大时间
    wrapper.le(!ObjectUtils.isEmpty(maxTime), Logs::getConsumingTime, maxTime)
      // 大于等于最小时间
      .ge(!ObjectUtils.isEmpty(minTime), Logs::getConsumingTime, minTime).orderByDesc(Logs::getId);
    return wrapper;
  }
}
